package constructor;

import java.lang.reflect.Constructor;

class Person {

    private String name;
    private String gender;
    private String birthday;

    private Person() {
    }

    public Person(String name){
        this.name = name;
    }

    public Person(String name, String gender, String birthday) {
        this.name = name;
        this.gender = gender;
        this.birthday = birthday;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    public String getBirthday() {
        return birthday;
    }

    public void setBirthday(String birthday) {
        this.birthday = birthday;
    }

    private void secrete(String content) {
        System.out.println("Show secrete is : " + content);
    }

    protected void sayHello(String msg) {
        System.out.println("hello," + msg);
    }

    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", gender='" + gender + '\'' +
                ", birthday='" + birthday + '\'' +
                '}';
    }


}

public class ReflectConstructorsDemo {

    public static void main(String[] args) throws Exception {
        Class clazz = Class.forName("constructor.Person");

        Constructor[] constructors =  clazz.getConstructors();
        System.out.println("------the result for getConstructors------------");
        for(Constructor constructor: constructors){
            System.out.println(constructor.toGenericString());
        }
        System.out.println("------the result for getDeclaredConstructors------------");
        constructors = clazz.getDeclaredConstructors();
        for(Constructor constructor: constructors){
            System.out.println(constructor.toGenericString());
        }

        Constructor conn = clazz.getConstructor(String.class);
        System.out.println("------the result for getConstructor------------");

        System.out.println(conn.toGenericString());
        Person p1 = (Person) conn.newInstance("张三");
        System.out.println(p1);

        //conn = clazz.getConstructor(); //错误，不能获取私有构造方法
        //System.out.println(conn.toGenericString());

        conn = clazz.getDeclaredConstructor();
        System.out.println("------the result for getDeclaredConstructor------------");

        System.out.println(conn.toGenericString());
        conn.setAccessible(true); //私有构造方法执行前必须设置可访问。

        Person p2 = (Person) conn.newInstance();
        System.out.println(p2);
    }
}
